package com.koron.standard.riskStock.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.koron.common.core.business.common.entity.TOrderNoMax;
import com.koron.common.core.business.common.service.TOrderNoMaxService;
import com.koron.standard.riskStock.bean.po.RiskStock;
import com.koron.standard.riskStock.service.RiskStockService;
import com.koron.standard.utils.StandardCodeTools;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author jzp
 * @since 2022/5/26
 */
@Slf4j
public class RiskStockListener extends AnalysisEventListener<RiskStock> {
    private static final int BATCH_COUNT = 100;

    private List<RiskStock> riskStockList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private final RiskStockService riskStockService;
    private final TOrderNoMaxService tOrderNoMaxService;

    public RiskStockListener(RiskStockService riskStockService, TOrderNoMaxService tOrderNoMaxService) {
        this.riskStockService = riskStockService;
        this.tOrderNoMaxService = tOrderNoMaxService;
    }

    @Override
    public void invoke(RiskStock data, AnalysisContext context) {
        riskStockList.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (riskStockList.size() >= BATCH_COUNT) {
            saveRiskStock();
            // 存储完成清理 list
            riskStockList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveRiskStock();
    }


    private void saveRiskStock() {
        if (riskStockList.size() == 0) {
            return;
        }
        // 1.1 获取当天最大编码
        TOrderNoMax maxNo = tOrderNoMaxService.peekNoMax(StandardCodeTools.riskStockPrefix, null, riskStockList.size());
        String prifix = StandardCodeTools.riskStockPrefix + maxNo.getDate();
        AtomicInteger atomicInteger = new AtomicInteger(maxNo.getMaxValue()- riskStockList.size());

        for (RiskStock riskStock : riskStockList) {
            riskStock.setCode(prifix + String.format("%0" + 4 + "d", atomicInteger.getAndIncrement()));
            riskStock.setNum(0);
            riskStock.setStatus(1);
        }
        log.info("{}条数据，开始存储数据库！", riskStockList.size());
        riskStockService.saveBatch(riskStockList);
        log.info("存储数据库成功！");
    }

}
